<?php

function go($city, $l = 1)
{
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => "http://restapi.amap.com/v3/config/district?keywords=$city&subdistrict=$l&extensions=base&key=f944a58171423a3f97b18f2d11e2e48c",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "GET",
        CURLOPT_HTTPHEADER => array(
            'cache-control: no-cache',
            'Time: ' . time(),
        ),
    ]);

    $res = curl_exec($ch);
    $res = json_decode($res);
    if ($res->info !== 'OK') {
        return false;
    }
    return $res;
}

$arr = go('台湾省', 2);
$i = 5100;
$pid = 29;

function tree($arr, &$i, $pid,$k = 1)
{
    foreach ($arr as $item) {
        echo '{"id":' . $i . ',"name":"' . $item->name . '","pid":' . $pid . '},' . "\n";
        echo ($k === 1)?"地级市\n":null;

        $i++;
        if (!empty($item->districts)) {
            tree($item->districts, $i, $i-1,2);
        }
    }
}

tree($arr->districts[0]->districts, $i, $pid);
